/*
 * Copyright © 2020-present LiuDanYang. All rights Reserved.
 */

/**
 * 解析时间到字符串
 * @param time {(Object|String|Number)}
 * @param cFormat {String}
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if ((typeof time === "string")) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if ((typeof time === "number") && (time.toString().length === 10)) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
}

/**
 * 拼接url
 * @param obj {Object} 要处理的参数
 * @param url {String} 链接地址
 * @returns {*}
 */
export function handleUrlQuery(url = "/", obj = {}) {
  if (!obj && typeof obj !== "object") {
    throw new Error("错误参数", "handleUrlQuery");
  }
  for (const objKey in obj) {
    url = updateQueryString(objKey, obj[objKey], url);
  }
  return url;
}

/**
 * 追加URL参数
 * @param key
 * @param value
 * @param url
 * @returns {string}
 */
export function updateQueryString(key, value, url) {
  if (!value) {
    return url;
  }
  const re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  const separator = url.indexOf("?") !== -1 ? "&" : "?";
  if (url.match(re)) {
    return url.replace(re, "$1" + key + "=" + value + "$2");
  } else {
    return url + separator + key + "=" + value;
  }
}


/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== "undefined") {
            const params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

/**
 * 判断是否是json字符串
 * @param json
 * @returns {boolean}
 */
export const isJSON = (json) => {
  return Object.prototype.toString.call(json).toLowerCase() === "[object string]";
};

/**
 * 判断是否为空
 * @param value
 * @returns {boolean|boolean}
 */
export const isEmpty = (value) => {
  return value === undefined || value === null || (typeof value === "string" && value.trim() === "") || (Array.isArray(value) && !value.length) || (typeof value === "object" && !Object.keys(value).length) || (typeof value === "number" && value === 0) || (typeof value === "boolean" && value === false) || (value instanceof Date && isNaN(value.getTime())) || (typeof value === "function" && value.toString().trim() === "");
};

/**
 * 移除字符串中的html标签
 * @param str
 * @returns {*|string}
 */
export const removeHtmlTag = (str) => {
  if (isEmpty(str)) {
    return "";
  }
  // 使用正则表达式一次性移除所有不需要的元素和空格
  str = str.replace(/<[^>]+>|&nbsp;|\s+|[\t\f\b]/g, "");
  // 去掉特殊符号
  str = str.replace(/[\u0000-\u0019]/g, "");
  // 去掉图片
  str = str.replace(/<img.*?(?:>|\/>)/gi, "");
  return str;
}

/**
 * 生成uuid
 * @returns {string}
 */
export const generateUUID = () => {
  let d = new Date().getTime();
  const uuid = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    // eslint-disable-next-line no-mixed-operators
    return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

/**
 * 拍照或从手机相册中选择图片
 * @param opts
 * @returns {Promise<unknown>}
 */
export const chooseImage = (opts) => {
  const {
    count,
    sizeType = ['original', 'compressed'],
    sourceType,
    extension
  } = opts
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count,
      sizeType,
      sourceType,
      extension,
      success(res) {
        resolve(normalizeChooseAndUploadFileRes(res, 'image'));
      },
      fail(res) {
        reject(res);
      },
    });
  });
}

function normalizeChooseAndUploadFileRes(res, fileType) {
  res.tempFiles.forEach((item, index) => {
    if (!item.name) {
      item.name = item.path.substring(item.path.lastIndexOf('/') + 1);
    }
    if (fileType) {
      item.fileType = fileType;
    }
    item.cloudPath = Date.now() + '_' + index + item.name.substring(item.name.lastIndexOf('.'));
  });
  if (!res.tempFilePaths) {
    res.tempFilePaths = res.tempFiles.map((file) => file.path);
  }
  return res;
}
